package cn.pconline.autoclub.util;

import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.LoggerFactory;

/**
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
public class TmplUtils {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(TmplUtils.class);

    public static String render(String baseTmplDir, String filePath, VelocityContext data) {
        VelocityEngine ve = new VelocityEngine();
        Properties properties = new Properties();
        properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, baseTmplDir);
        properties.setProperty(VelocityEngine.INPUT_ENCODING, "UTF-8");
        properties.setProperty(VelocityEngine.OUTPUT_ENCODING, "UTF-8");
        try {
            ve.init(properties);
        } catch (Exception ex) {
            log.error("init velocity engine fail!", ex);
        }
        Template t;
        try {
            t = ve.getTemplate(filePath);
            StringWriter writer = new StringWriter();
            t.merge(data, writer);
            return writer.toString();
        } catch (Exception ex) {
            log.error("render ERROR!", ex);
        }
        return "";
    }
}
